<script setup lang="ts">
import {
    useReformInstallationApplyAuditDetail,
    useReformInstallationApplyAuditing,
    useReformInstallationApplyExport,
    useReformInstallationApplyList,
} from "@fl/api/elevator-api";
import { useGetCascadeData } from "@fl/api/elevator-api/verify";
import { SearchForm, SearchTable } from "@fl/components";
import FlUpload from "@fl/components/fl-upload.vue";
import { useMessage } from "@fl/hooks/web/use-message";
import { hasPermi } from "@fl/utils/has-permi";
import dayjs from "dayjs";
import { cloneDeep } from "lodash-es";
import type { OptionsType, PlusColumn } from "plus-pro-components";
import type { VxeGridProps, VxePagerEvents } from "vxe-table";
import MergeDialog from "./components/merge-dialog.vue";
import MergeRecords from "./components/merge-records.vue";
import ShowMap from "../history/components/map.vue";

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: "retrofit-elevator-requirement-list",
});
const projectName = ref("");
const positionInfo = ref<any>(); // 经纬度信息

const { createMessage } = useMessage();

type IinitialState = {
    areaCode?: string;
    streetCode?: string;
    communityCode?: string;
    projectId?: string;
    building?: string;
    unit?: string;
    status: string;
};
type IForm = {
    id?: string;
    info: {
        files: { url: string; name: string }[];
        formDate?: string;
    };
    result?: boolean;
    status?: string;
};
function disabledDate(date: any) {
    return date > new Date();
}
const tableRef = ref();

const router = useRouter();
const initialState = {
    areaCode: "",
    streetCode: "",
    communityCode: "",
    projectId: "",
    building: "",
    unit: "",
    status: "",
};
const state = ref<IinitialState>(cloneDeep(initialState));
const searchConditions = ref<IinitialState>(cloneDeep(initialState));

// const initialPage = {
//   currentPage: 1,
//   pageSize: 10,
//   total: 0,
// };
// const tablePage = ref(cloneDeep(initialPage));
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});

// 级联
const getAreaOptionsParams = computed(() => ({
    targetLabel: "area",
}));
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: "street",
}));
const getCommunityOptionsParams = computed(() => ({
    streetCode: state.value.streetCode,
    targetLabel: "community",
}));
const getProjectOptionsParams = computed(() => ({
    communityCode: state.value.communityCode,
    // areaCode: state.value.areaCode,
    // streetCode: state.value.streetCode,
    targetLabel: "project",
    projectName: projectName.value,
}));
const getBuildingOptionsParams = computed(() => ({
    projectId: state.value.projectId,
    targetLabel: "building",
}));
const getUnitOptionsParams = computed(() => ({
    buildingId:buildingOptions.value && state.value.building
  ? (buildingOptions.value.find(item => item.label === state.value.building)?.buildingId ?? '')
  : '',
    building: state.value.building,
    targetLabel: "unit",
}));
const { data: areaOptions } = useGetCascadeData(getAreaOptionsParams);
const { data: streetOptions } = useGetCascadeData(getStreetOptionsParams, "areaCode");
const { data: communityOptions } = useGetCascadeData(
    getCommunityOptionsParams,
    "streetCode"
);
const { data: projectOptions, isLoading: projectLoading } = useGetCascadeData(
    getProjectOptionsParams,
    "projectName"
);
const { data: buildingOptions } = useGetCascadeData(
    getBuildingOptionsParams,
    "projectId"
);
const { data: unitOptions } = useGetCascadeData(getUnitOptionsParams, "building");
function projectSearch(keyword) {
    projectName.value = keyword;
}
watch(
    () => state.value.areaCode,
    () => {
        const {
            building,
            communityCode,
            projectId,
            streetCode,
            unit,
            ...data
        } = state.value;
        state.value = cloneDeep(data);
    }
);

watch(
    () => state.value.streetCode,
    () => {
        const { building, communityCode, projectId, unit, ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

watch(
    () => state.value.communityCode,
    () => {
        const { building, projectId, unit, ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

watch(
    () => state.value.projectId,
    () => {
        const { building, unit, ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

watch(
    () => state.value.building,
    () => {
        const { unit, ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

const params = computed(() => ({
    ...searchConditions.value,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    success: true,
    orderBy: "create_time", // 根据创建时间排序
    orderType: "desc", // 降序
}));
const detailParams = ref({
    id: "",
});
const { data, isLoading } = useReformInstallationApplyList(params);
const { data: detail, isLoading: detailLoading } = useReformInstallationApplyAuditDetail(
    detailParams
);
const records = ref<any>();
const drawerFlag = ref<any>(false);
const recordsDrawervisible = ref<any>(false);
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage;
    tablePage.pageSize = pageSize;
};

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records);
        tablePage.total = data.value.total!;
    }
    if (detail.value) {
        form.value = {
            id: detailParams.value.id,
            info: {
                files: cloneDeep(detail.value.info?.files ?? []),
                formDate: detail.value.info?.formDate,
            },
            result: true,
            status: detail.value.status,
        };
    }
});

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: "所在区",
        options: areaOptions as OptionsType,
        prop: "areaCode",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: "街道",
        options: streetOptions as OptionsType,
        prop: "streetCode",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: "社区",
        options: communityOptions as OptionsType,
        prop: "communityCode",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        // fieldProps: {
        //     filterable: true,
        // },
        label: "小区",
        // options: projectOptions as OptionsType,
        prop: "projectId",
        // valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: "栋",
        options: buildingOptions as OptionsType,
        prop: "building",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: "单元",
        options: unitOptions as OptionsType,
        prop: "unit",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        label: "审核状态",
        prop: "status",
        valueType: "select",
        options: [
            {
                label: "待处理",
                value: 20,
            },
            {
                label: "已满足表决要求",
                value: 300,
            },
            {
                label: "暂不满足表决要求",
                value: 310,
            },
        ],
    },
    {
        colProps: {
            span: 6,
        },
        label: "编号",
        prop: "applyNo",
    },
];
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { type: "checkbox", width: 50 },
        { field: "applyNo", title: "编号" },
        { field: "areaName", title: "所在区" },
        { field: "streetName", title: "街道" },
        { field: "communityName", title: "社区" },
        { field: "projectName", title: "小区" },
        { field: "building", slots: { default: "building" }, title: "栋-单元" },
        // { field: 'natureNo', title: '自然栋编号' },
        { field: "status", slots: { default: "status" }, title: "审核状态" },
        { field: "updateTime", title: "更新时间" },
        { slots: { default: "operate" }, title: "操作", width: 200 },
    ],
});
const form = ref<IForm>({
    id: "",
    info: {
        files: [],
        formDate: "",
    },
    result: true,
    status: "",
});

function submit() {
    searchConditions.value = cloneDeep(state.value);
    resetTablePage();
}

function reset() {
    state.value = cloneDeep(initialState);
    searchConditions.value = cloneDeep(initialState);
    resetTablePage();
}

function resetTablePage() {
    tablePage.currentPage = 1;
    tablePage.pageSize = 10;
}

function toDetail(row: any) {
    router.push({ name: "requirement-detail", params: { id: row.id } });
}
const isEdit = ref(false);
function showDrawer(row: any, bool: boolean) {
    detailParams.value = cloneDeep(row);
    drawerFlag.value = computed(() => !detailLoading.value);
    isEdit.value = bool;
    positionInfo.value = {
        longitude: Number(row.longitude),
        latitude: Number(row.latitude),
    };
}
function downLoad() {
    window.open(detail.value.files[0].fileUrl);
}
const { isPending, mutate } = useReformInstallationApplyAuditing();
function confirmClick() {
    const params = {
        ...form.value,
    };
    if (params.result === null) {
        ElMessage({
            message: "请选择业主意见征询结果",
            type: "error",
        });
        return;
    }
    if (
        params.result === true &&
        (!params.info.formDate || params.info.files.length === 0)
    ) {
        ElMessage({
            message: "请上传相关资料",
            type: "error",
        });
        return;
    }
    mutate(params, {
        onSuccess: () => {
            ElMessage({
                message: "提交成功",
                type: "success",
            });
            drawerFlag.value = false;

            detailParams.value.id = "";
        },
    });
}
function preview(url) {
    window.open(url);
}
function close() {
    drawerFlag.value = false;
    detailParams.value.id = "";
}

watch(
    () => drawerFlag.value,
    () => {
        if (!drawerFlag.value) {
            positionInfo.value = {
                longitude: null,
                latitude: null,
            };
        }
    }
);

function isMoreThanThreeMonthsAgo(date) {
    // 上报时间超过六个月未处理需要标红
    const threeMonthAgo = dayjs().subtract(6, "month");
    return dayjs(date).isBefore(threeMonthAgo);
}
const mergeVisible = ref(false);
const mergeList = ref([]);
function merge() {
    const $table = tableRef.value?.tableInstance;
    if ($table) {
        const selectRecords = $table.getCheckboxRecords();
        if (selectRecords.length) {
            const uniqueProjectIds = selectRecords.filter(
                (item, index, self) =>
                    index === self.findIndex((t) => t.projectId === item.projectId)
            );
            // console.log(selectRecords.value.every((i) => i.status === 300));
            if (uniqueProjectIds.length > 1) {
                createMessage.warning("请选择同一所在区、街道、社区、小区的记录");
                return;
            }
            mergeVisible.value = true;
            mergeList.value = selectRecords;
        } else {
            createMessage.warning("请至少选择一条数据");
        }
    }
}
// 导出
const exportParams = computed(() => ({
    ...searchConditions.value,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    success: true,
    orderBy: "create_time", // 根据创建时间排序
    orderType: "desc", // 降序
}));
const { isPending: isExportPending, mutateAsync } = useReformInstallationApplyExport(
    exportParams
);
async function exportData() {
    const res = await mutateAsync();
    if (res) {
        const objectUrl = URL.createObjectURL(res);
        location.href = objectUrl;
        URL.revokeObjectURL(objectUrl);
    }
}
</script>

<template>
    <ElCard class="mb-20" shadow="never">
        <SearchForm
            v-model="state"
            submit-text="搜索"
            :columns="columns"
            @reset="reset"
            @submit="submit"
        >
            <template #plus-field-projectId>
                <el-select
                    v-model="state.projectId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="直接搜小区,无需选区域"
                    remote-show-suffix
                    :remote-method="projectSearch"
                    :loading="projectLoading"
                >
                    <el-option
                        v-for="item in projectOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </template>
        </SearchForm>
    </ElCard>

    <ElCard shadow="never">
        <SearchTable
            ref="tableRef"
            v-bind="gridOptions"
            v-model:pager="tablePage"
            :loading="isLoading"
            :data="records"
            @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <ElButton type="primary" @click="merge"> 合并 </ElButton>

                <ElButton type="primary" @click="recordsDrawervisible = true">
                    合并记录
                </ElButton>
                <ElButton
                    type="primary"
                    plain
                    :loading="isExportPending"
                    @click="exportData"
                >
                    <div class="i-iconamoon:upload size-16" />
                    导出
                </ElButton>
            </template>

            <template #building="{ row }"> {{ row.building }}-{{ row.unit }} </template>

            <template #status="{ row }">
                <span
                    :class="
                        row.status === 20 && isMoreThanThreeMonthsAgo(row.createTime)
                            ? 'color-red'
                            : ''
                    "
                >
                    {{
                        row.status === 20
                            ? "待处理"
                            : row.status === 300
                            ? "已满足表决要求"
                            : "暂不满足表决要求"
                    }}</span
                >

                <!-- {{ isMoreThanThreeMonthsAgo(row.createTime) }} -->
            </template>

            <template #operate="{ row }">
                <el-button
                    v-if="hasPermi('需求上报-处理')"
                    text
                    type="primary"
                    @click="showDrawer(row, true)"
                >
                    {{ row.status === 20 ? "处理" : "修改" }}
                </el-button>

                <el-button text @click="toDetail(row)"> 详情 </el-button>

                <el-button
                    v-if="hasPermi('需求上报-查看')"
                    text
                    @click="showDrawer(row, false)"
                >
                    查看
                </el-button>
            </template>
        </SearchTable>
    </ElCard>

    <ElDrawer v-model="drawerFlag" direction="rtl" size="30%">
        <template #header>
            <div class="text-24 text-black font-600">
                {{ isEdit ? "处理" : "查看" }}
            </div>
        </template>

        <template v-if="isEdit" #default>
            <div class="mb-30">
                <div class="mb-20 text-black font-600">业主意见征询结果</div>

                <div class="p-12 border border-[#eee]">
                    <el-radio v-model="form.result" :value="true" size="large">
                        已满足法定表决比例要求
                    </el-radio>
                    <!-- <el-radio v-model="form.result" :value="false" size="large">
            暂不满足法定表决比例要求
          </el-radio> -->
                </div>
            </div>

            <div v-if="form.result === true" class="px-12 pt-12 border border-[#eee]">
                <div class="mb-24 text-black font-600">
                    相关资料上传
                    <span class="text-12 text-[#939393] font-400"
                        >(点击文件名直接下载模板)</span
                    >
                </div>

                <div class="mb-24">
                    完成业主意愿征询时间
                    <div class="pt12">
                        <el-date-picker
                            v-model="form.info.formDate"
                            type="date"
                            placeholder="请选择时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            :disabled-date="disabledDate"
                        />
                    </div>
                </div>

                <div>
                    <div
                        class="mb-12 color-[#006DCC] flex-1"
                        style="
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                        "
                    >
                        <span class="w-full cursor-pointer" @click="downLoad">
                            既有住宅加装电梯单元业主签字意见表
                        </span>
                    </div>

                    <div class="flex flex-1 items-center">
                        <FlUpload
                            :key="String(form.id)"
                            v-model="form.info.files"
                            :limit="10"
                            accept="*"
                            list-type="text"
                            :tips="false"
                        />
                    </div>
                </div>
            </div>
        </template>

        <template v-else #default>
            <el-form :model="form" label-position="top">
                <el-form-item label="业主意见征询结果：" prop="naresultme">
                    {{
                        form.result && !form.info.formDate
                            ? "待处理"
                            : form.result
                            ? "已满足法定表决比例要求"
                            : "暂不满足法定表决比例要求"
                    }}
                </el-form-item>

                <el-form-item label="完成业主意愿征询时间：" prop="formDate">
                    {{ form.info.formDate }}
                </el-form-item>

                <el-form-item
                    label="既有住宅加装电梯单元业主签字意见表："
                    prop="formDate"
                >
                    <template v-if="form.info.files.length > 0">
                        <div
                            v-for="item in form.info.files"
                            class="file-name"
                            @click="preview(item.url)"
                        >
                            {{ item.name }}
                        </div>
                    </template>
                </el-form-item>
            </el-form>

            <!-- 地图 -->
            <div v-if="positionInfo?.longitude > 0" class="abs">
                <ShowMap
                    v-model:longitude="positionInfo.longitude"
                    v-model:latitude="positionInfo.latitude"
                />
            </div>
        </template>

        <template v-if="isEdit" #footer>
            <div style="flex: auto">
                <el-button type="primary" :is-loading="isPending" @click="confirmClick">
                    提交
                </el-button>

                <el-button @click="close"> 取消 </el-button>
            </div>
        </template>
    </ElDrawer>

    <MergeDialog
        v-if="mergeVisible"
        v-model:show="mergeVisible"
        :initMergeList="mergeList"
    />
    <MergeRecords v-if="recordsDrawervisible" v-model:visible="recordsDrawervisible" />
</template>

<style lang="scss" scoped>
.file-name {
    display: inline-block;
    padding: 0 4px;
    cursor: pointer;
    width: 100px;
    overflow: hiddden;
    text-overflow: ellipsis;

    white-space: nowrap;
    &:hover {
        color: #da0004;
        background-color: #f5f7fa;
    }
}
.abs {
    position: fixed;
    top: 20px;
    right: 31%;
    background: #fff;
    width: calc(66vw - 200px);
    height: 94vh;
}
</style>
